<template>
  <div>
    <img src="@/assets/logo.png" alt="" />
    <h2>欢迎 登录 odoojs 平台</h2>

    <a-form :model="formState" name="basic" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }" autocomplete="off"
      @finish="onFinish" @finishFailed="onFinishFailed">
      <a-form-item name="database" label="数据库" :rules="[{ required: true, message: 'Please select one database!' }]">
        <a-select v-model:value="formState.database" :options="databaseOptions" />
      </a-form-item>

      <a-form-item label="Username" name="username" :rules="[{ required: true, message: 'Please input your username!' }]">
        <a-input v-model:value="formState.username" />
      </a-form-item>

      <a-form-item label="Password" name="password" :rules="[{ required: true, message: 'Please input your password!' }]">
        <a-input-password v-model:value="formState.password" />
      </a-form-item>
      <!--
      <a-form-item name="remember" :wrapper-col="{ offset: 8, span: 16 }">
        <a-checkbox v-model:checked="formState.remember">
          Remember me
        </a-checkbox>
      </a-form-item> -->

      <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
        <a-button type="primary" html-type="submit">Submit</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup>
import api from '@/odoojs/index.js'
import { useRouter } from 'vue-router'
const router = useRouter()

console.log(api)

import { reactive, ref, onMounted } from 'vue'
const formState = reactive({
  database: 'T1',
  username: 'admin',
  password: '123456'
  // remember: true
})

const databaseOptions = ref([])
async function load_databaseOptions() {
  const ops = await api.web.database.list()
  databaseOptions.value = ops.map(item => {
    return { value: item, label: item }
  })

  if (!formState.database) {
    if (ops.length) {
      formState.database = ops[0]
    }
  }
}

async function handleLogin(values) {
  const { database: db, username: login, password } = values
  const kw = { db, login, password }
  const info = await api.login(kw)
  return info
}

async function onFinish(values) {
  console.log('Success:', values)

  const info = await handleLogin(values)

  if (info) {
    //
    console.log(info)
    router.push({ path: '/' })
  } else {
    alert('err')
  }
}
function onFinishFailed(errorInfo) {
  console.log('Failed:', errorInfo)
}

onMounted(async () => {
  load_databaseOptions()
})
</script>
<style scoped></style>
